﻿using GalaSoft.MvvmLight;
using WP7Contrib.Collections;
using GalaSoft.MvvmLight.Command;
using System.Windows.Controls;
using System.Net;
using Microsoft.Phone.Net.NetworkInformation;
using System;

namespace CDFWPUG.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class pageNewsViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the pageNewsViewModel class.
        /// </summary>
        public pageNewsViewModel()
        {
            _NewsItems = new ObservableCollection<Model.FeedItem>();
            NewsItemSelectedCommand = new RelayCommand<SelectionChangedEventArgs>(HandleNewsItemSelectedCommand);
            NewsRefreshCommand = new RelayCommand(HandleNewsRefreshCommand);

            if (IsInDesignMode)
            {
                _NewsItems = Helpers.NewsHelper.Test_GetNewsFeed();
            }
            else
            {
                // Code runs "for real": Connect to service, etc...
                LoadNews();
            }


           

        }

        public override void Cleanup()
        {
            // Clean own resources if needed

            base.Cleanup();
        }


        #region properties

        private ObservableCollection<Model.FeedItem> _NewsItems;
        public ObservableCollection<Model.FeedItem> NewsItems
        {
            get
            {
                return _NewsItems;
            }
            set
            {
                if (_NewsItems != value)
                {
                    _NewsItems = value;
                    RaisePropertyChanged("NewsItems");
                }   
            }

        }

        private Model.FeedItem _SelectedNewsItem;
        public Model.FeedItem SelectedNewsItem
        {
            get
            {
                return _SelectedNewsItem;
            }
            set
            {
                _SelectedNewsItem = value;
                RaisePropertyChanged("SelectedNewsItem");
            }
        }

        private Boolean _NewsLoading;
        public Boolean NewsLoading
        {
            get { return _NewsLoading; }
            set
            {
                if (_NewsLoading != value)
                {
                    _NewsLoading = value;
                    RaisePropertyChanged("NewsLoading");
                }

            }
        }

        private String _NewsMessage;
        public String NewsMessage
        {
            get { return _NewsMessage; }
            set
            {
                if (_NewsMessage != value)
                {
                    _NewsMessage = value;
                    RaisePropertyChanged("NewsMessage");
                }

            }
        }
        


        #endregion

        #region Commands

        public RelayCommand<SelectionChangedEventArgs> NewsItemSelectedCommand { get; private set; }
        private void HandleNewsItemSelectedCommand(SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                string address = SelectedNewsItem.Link;
                Helpers.FunctionsHelper.CreateWebsiteTask(address);
            }
        }


        public RelayCommand NewsRefreshCommand { get; private set; }
        private void HandleNewsRefreshCommand()
        {
            UpdateNews();
        }


        #endregion



        public void  LoadNews()
        {

            if (Helpers.IsolatedStorageHelper.FileExists("NewsItems.xml"))
                {
                    var results = Helpers.NewsHelper.GetNewsFromIsolatedStorage();
                    NewsItems.Clear();
                    foreach (var item in results)
                    {
                        NewsItems.Add(item);
                    }
                }
                else
                {
                    //no file in isolated storage so download it
                    UpdateNews();
                }

        }

        public  void UpdateNews()
        {
            WebClient newsFeed = new WebClient();
            bool hasNetworkConnection = NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None;
            string xmldata = "http://feeds.feedburner.com/WindowsPhoneUG?format=xml";
            NewsItems.Clear();
            NewsLoading = true;

            if (hasNetworkConnection == true)
            {
                newsFeed.DownloadStringCompleted += new DownloadStringCompletedEventHandler(newsFeed_DownloadStringCompleted);
                newsFeed.DownloadStringAsync(new Uri(xmldata));
            }
            else
            {
                NewsMessage = "There is currently no network coverage, try again later";
            }
            NewsLoading = false;
        }

        void newsFeed_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                string xml = e.Result;

                if (Helpers.IsolatedStorageHelper.FileExists("NewsItems.xml"))
                {
                    Helpers.IsolatedStorageHelper.DeleteFile("NewsItems.xml");
                }

                Helpers.IsolatedStorageHelper.SaveFile("NewsItems.xml", xml);
                LoadNews();
            }
            else
            {
                NewsMessage = "Opps! There was a problem while getting the news. Please try again later";
            }
        }

      


    }
}